package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmii.sjw.department.control.jsc.exception.BaseException;
import com.cmii.sjw.department.control.jsc.mapper.ConferenceParticipantMapper;
import com.cmii.sjw.department.control.jsc.mapper.DistrictSchoolMapper;
import com.cmii.sjw.department.control.jsc.mapper.SchoolAdminMapper;
import com.cmii.sjw.department.control.jsc.model.ConferenceParticipant;
import com.cmii.sjw.department.control.jsc.model.DistrictSchool;
import com.cmii.sjw.department.control.jsc.model.SchoolAdmin;
import com.cmii.sjw.department.control.jsc.model.params.SchoolAdminParams;
import com.cmii.sjw.department.control.jsc.model.params.UniversitiesAdminParams;
import com.cmii.sjw.department.control.jsc.service.SchoolAdminService;
import com.cmii.sjw.department.control.jsc.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jfh
 * @Date 2025年06月07日 11:58
 */
@Slf4j
@Service
public class SchoolAdminServiceImpl implements SchoolAdminService {

    @Autowired
    private DistrictSchoolMapper districtSchoolMapper;

    @Autowired
    private SchoolAdminMapper schoolAdminMapper;

    @Autowired
    private ConferenceParticipantMapper conferenceParticipantMapper;


    @Override
    public List<DistrictSchool> districtList() {
        //按照所属区县名称进行去重查询列表
        return districtSchoolMapper.selectList(
                new QueryWrapper<DistrictSchool>().select("distinct district, district_code")
        );
    }

    @Override
    public List<DistrictSchool> schoolList(String district) {
        return districtSchoolMapper.selectList(
                new QueryWrapper<DistrictSchool>().eq("district", district)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> ordinarySchoolAdminSave(List<SchoolAdminParams> paramsList) {
        if (paramsList == null || paramsList.isEmpty()) {
            return Result.error("参数列表不能为空");
        }

        try {
            List<SchoolAdmin> schoolAdminList = paramsList.stream()
                    .filter(Objects::nonNull)
                    .map(this::convertToSchoolAdmin)
                    .collect(Collectors.toList());

            boolean success = schoolAdminMapper.insertBatch(schoolAdminList);
            return success ? Result.success("保存成功") : Result.error("保存失败");
        } catch (Exception e) {
            // 可根据实际需求记录日志：
            log.error("保存失败", e);
            throw new BaseException(e.getMessage());
//            return Result.error("保存过程中发生异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> universitiesAdminSave(List<UniversitiesAdminParams> paramsList) {
        if (paramsList == null || paramsList.isEmpty()) {
            return Result.error("参数列表不能为空");
        }

        try {
            List<SchoolAdmin> schoolAdminList = paramsList.stream()
                    .filter(Objects::nonNull)
                    .map(this::convertToUniversitiesAdmin)
                    .collect(Collectors.toList());

            boolean success = schoolAdminMapper.insertBatch(schoolAdminList);
            return success ? Result.success("保存成功") : Result.error("保存失败");
        } catch (Exception e) {
            // 可根据实际需求记录日志：
            log.error("保存失败", e);
            throw new BaseException(e.getMessage());
//            return Result.error("保存过程中发生异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> conferenceParticipantSave(List<ConferenceParticipant> paramsList) {
        if (paramsList == null || paramsList.isEmpty()) {
            return Result.error("参数列表不能为空");
        }

        try {
            paramsList.forEach(conferenceParticipant -> conferenceParticipant.setNeetingsName("高校核心业务梳理及业务事项编目专题培训会主会场参会回执"));
            boolean success = conferenceParticipantMapper.insertBatch(paramsList);
            return success ? Result.success("保存成功") : Result.error("保存失败");
        } catch (Exception e) {
            // 可根据实际需求记录日志：
            log.error("保存失败", e);
            throw new BaseException(e.getMessage());
//            return Result.error("保存过程中发生异常: " + e.getMessage());
        }
    }

    @Override
    public void validation() {
        List<SchoolAdmin> schoolAdmins = schoolAdminMapper.selectList(
                new QueryWrapper<SchoolAdmin>().eq("type", "4")
        );
        schoolAdmins.forEach(schoolAdmin -> {
            schoolAdmin.setDescription(getUserInfoByMobiles(schoolAdmin.getPhoneNumber(),String.valueOf(schoolAdmin.getAccountId())));
        });
        schoolAdminMapper.updateBatch(schoolAdmins);

    }


    private String getUserInfoByMobiles(String phoneNumber,String accountId) {
        String url = "http://23.210.23.1:8081/smart_edu_gov/sjtb/getUserInfoByMobiles";

        StringBuilder params = new StringBuilder();
        params.append("?mobiles=").append(phoneNumber);
        String apiResult = HttpUtil.createPost(url + params.toString())
//                .header(Header.AUTHORIZATION, Header.AUTHORIZATION.getValue())
                .execute()
                .body();

        log.info("apiResult: {}", apiResult);
        JSONObject response = JSON.parseObject(apiResult);
        if (!"200".equals(response.getString("code"))) {
            return "获取用户信息失败";
        }
//        validateResponse(response, "外层响应");

        JSONObject dataResponse = JSON.parseObject(response.getString("data"));
//        validateResponse(dataResponse, "数据层响应");

        log.info("aaaa:{},xxxxxxxxxx: {}",phoneNumber, dataResponse.getString("data"));
        if (dataResponse.getString("data").equals("[]")) {
            return "账号不存在";
        }
        //[{"accountId":1166436,"mobile":"17783611856","name":"屈和杨","id":1927982176514560002,"employeeCode":"GE_1927982176501563392","username":"quheyang856"}]
        JSONArray accountData = JSON.parseArray(dataResponse.getString("data"));



        String uId = accountData.getJSONObject(0).getString("accountId");
//        JSONObject accountData = JSON.parseObject(dataResponse.getString("data"));

        return uId.equals(accountId) ? "账号核实无误" : "账号核实有误";
    }
    /**
     * 验证响应
     * @param response 响应对象
     * @param layer 响应层级
     */
    private void validateResponse(JSONObject response, String layer) {
        if (!"200".equals(response.getString("code"))) {
            String errorMsg = String.format("%s验证响应错误, code:%s, message:%s",
                    layer, response.getString("code"), response.getString("msg"));
            log.error(errorMsg);
            throw new BaseException(errorMsg);
        }
    }

    private SchoolAdmin convertToUniversitiesAdmin(UniversitiesAdminParams params) {
        SchoolAdmin schoolAdmin = new SchoolAdmin();
        schoolAdmin.setSchoolCode(params.getUniversitiesCode());
        schoolAdmin.setSchoolName(params.getUniversitiesName());
        schoolAdmin.setLastName(params.getLastName());
        schoolAdmin.setPhoneNumber(params.getPhoneNumber());
        schoolAdmin.setAccountId(params.getAccountId());
        schoolAdmin.setPosition(params.getPosition());
        schoolAdmin.setPermissions(params.getPermissions());
        schoolAdmin.setDescription(params.getDescription());
        schoolAdmin.setType("3");
        return schoolAdmin;
    }

    private SchoolAdmin convertToSchoolAdmin(SchoolAdminParams params) {
        SchoolAdmin schoolAdmin = new SchoolAdmin();
        schoolAdmin.setDistrictCode(params.getDistrictCode());
        schoolAdmin.setDistrict(params.getDistrict());
        schoolAdmin.setSchoolCode(params.getSchoolCode());
        schoolAdmin.setSchoolName(params.getSchoolName());
        schoolAdmin.setLastName(params.getLastName());
        schoolAdmin.setPhoneNumber(params.getPhoneNumber());
        schoolAdmin.setAccountId(params.getAccountId());
        schoolAdmin.setOrgName(params.getOrgName());
        schoolAdmin.setType("4");
        return schoolAdmin;
    }
}
